/*
 * Copyright (C) 2014 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package com.tushen.datacenter.ts;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.common.util.*;
import com.common.view.ColorUtil;
import com.common.view.MyGridView;
import com.common.view.PopwindowUtil;
import com.common.view.TimeTextView;
import com.common.view.ViewAdjust;
import com.common.view.piecharta.IPieElement;
import com.common.view.piecharta.PieChart;
import com.common.view.piecharta.TestEntity;
import com.common.viewinject.ViewInject;
import com.common.viewinject.ViewUtils;
import com.tushen.datacenter.ts.data.DataListener;
import com.tushen.datacenter.ts.data.DataManager;

import org.apache.commons.codec.binary.StringUtils;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.lang.ref.WeakReference;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.util.*;

public class MainActivity extends Activity {

    private static final String TAG = "MainActivity";


    private  Activity mContext;
    private View rootView;

    @ViewInject(value = R.id.left_lgo_iv)
    private ImageView mLeftLogoView;

    @ViewInject(value = R.id.date)
    private TimeTextView mTimeTextView;
    @ViewInject(value = R.id.poster)
    private ImageView mPosterView;
    @ViewInject(value = R.id.detail_1)
    private TextView mDetailView1;
    @ViewInject(value = R.id.detail_2)
    private TextView mDetailView2;
    @ViewInject(value = R.id.detail_3)
    private TextView mDetailView3;
    @ViewInject(value = R.id.detail_4)
    private TextView mDetailView4;
    @ViewInject(value = R.id.detail_5)
    private TextView mDetailView5;
    @ViewInject(value = R.id.detail_6)
    private TextView mDetailView6;
    @ViewInject(value = R.id.detail_7)
    private TextView mDetailView7;
    @ViewInject(value = R.id.detail_8)
    private TextView mDetailView8;

    @ViewInject(value = R.id.worker_cnt_1_1)
    private TextView mWoker1_1;
    @ViewInject(value = R.id.worker_cnt_1_2)
    private TextView mWoker1_2;
    @ViewInject(value = R.id.worker_cnt_1_3)
    private TextView mWoker1_3;
    @ViewInject(value = R.id.worker_cnt_1_4)
    private TextView mWoker1_4;

    @ViewInject(value = R.id.worker_cnt_2_1)
    private TextView mWoker2_1;
    @ViewInject(value = R.id.worker_cnt_2_2)
    private TextView mWoker2_2;
    @ViewInject(value = R.id.worker_cnt_2_3)
    private TextView mWoker2_3;
    @ViewInject(value = R.id.worker_cnt_2_4)
    private TextView mWoker2_4;


    @ViewInject(value = R.id.worker_cnt_3_1)
    private TextView mWoker3_1;
    @ViewInject(value = R.id.worker_cnt_3_2)
    private TextView mWoker3_2;
    @ViewInject(value = R.id.worker_cnt_3_3)
    private TextView mWoker3_3;
    @ViewInject(value = R.id.worker_cnt_3_4)
    private TextView mWoker3_4;

    @ViewInject(value = R.id.manager_cnt_1_1)
    private TextView mManager1_1;
    @ViewInject(value = R.id.manager_cnt_1_2)
    private TextView mManager1_2;
    @ViewInject(value = R.id.manager_cnt_1_3)
    private TextView mManager1_3;
    @ViewInject(value = R.id.manager_cnt_1_4)
    private TextView mManager1_4;

    @ViewInject(value = R.id.manager_cnt_2_1)
    private TextView mManager2_1;
    @ViewInject(value = R.id.manager_cnt_2_2)
    private TextView mManager2_2;
    @ViewInject(value = R.id.manager_cnt_2_3)
    private TextView mManager2_3;
    @ViewInject(value = R.id.manager_cnt_2_4)
    private TextView mManager2_4;


    @ViewInject(value = R.id.manager_cnt_3_1)
    private TextView mManager3_1;
    @ViewInject(value = R.id.manager_cnt_3_2)
    private TextView mManager3_2;
    @ViewInject(value = R.id.manager_cnt_3_3)
    private TextView mManager3_3;
    @ViewInject(value = R.id.manager_cnt_3_4)
    private TextView mManager3_4;

    @ViewInject(value = R.id.age_1)
    private ImageView mAageIv1;
    @ViewInject(value = R.id.age_2)
    private ImageView mAageIv2;
    @ViewInject(value = R.id.age_3)
    private ImageView mAageIv3;
    @ViewInject(value = R.id.age_4)
    private ImageView mAageIv4;
    @ViewInject(value = R.id.age_percent_1)
    private TextView mAagePercent1;
    @ViewInject(value = R.id.age_percent_2)
    private TextView mAagePercent2;
    @ViewInject(value = R.id.age_percent_3)
    private TextView mAagePercent3;
    @ViewInject(value = R.id.age_percent_4)
    private TextView mAagePercent4;

    @ViewInject(value = R.id.sex_male)
    private TextView mSexMale;
    @ViewInject(value = R.id.sex_female)
    private TextView mSexFemale;

    @ViewInject(value = R.id.mPieChart)
    private PieChart mPieChart;

    @ViewInject(value = R.id.mPieGrid)
    private MyGridView mPieGridView;

    @ViewInject(value = R.id.compony_group)
    private ViewGroup mCompanyGroupView;

    private LayoutInflater mInflater;
    //private final MyHandler mHandler = new MyHandler(this);

    private JSONArray mComponyJsonArray = new JSONArray();
    private int mLastShowComponyIndex = 0;

    private UdpReceiveThread udpReceiveThread;

    MessageHandler handler = new MessageHandler(this);

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        EventBus.getDefault().register(this);
        mContext = this;
        mInflater = LayoutInflater.from(this);
        rootView = findViewById(R.id.root_layout);
        ViewAdjust.adjustLayoutParams(this, rootView);
        ViewUtils.inject(this, rootView);

        mPieGridView.setAdapter(new ItemAdapter(mInflater));
        handler.sendEmptyMessageDelayed(0, 500);

        for (int i = 0; i < 10; i++) {
            View view = mInflater.inflate(R.layout.company_item, null);
            ViewAdjust.adjustLayoutParams(mInflater.getContext(), view.findViewById(R.id.inner_root_view));
            mCompanyGroupView.addView(view);
        }

    }

    private String getMixString(String str){
        if(str == null || str.length() < 8 ){
            return str;
        }
        String ret = "";
        ret = str.substring(0,str.length()-8);
        ret += "****";
        ret += str.substring(str.length()-4,str.length());
        return ret;
    }

    private void setCntText(Integer count, TextView t1, TextView t2, TextView t3, TextView t4) {
        String countStr = String.valueOf(count);
        if(countStr.length()  == 1){
            t1.setText(countStr.charAt(0)+"");
            t2.setText("");
            t3.setText("");
            t4.setText("");
        }else if(countStr.length()  == 2){
            t1.setText(countStr.charAt(0)+"");
            t2.setText(countStr.charAt(1)+"");
            t3.setText("");
            t4.setText("");
        }else if( countStr.length()  == 3){
            t1.setText(countStr.charAt(0)+"");
            t2.setText(countStr.charAt(1)+"");
            t3.setText(countStr.charAt(2)+"");
            t4.setText("");
        }else if(countStr.length()  == 4){
            t1.setText(countStr.charAt(0)+"");
            t2.setText(countStr.charAt(1)+"");
            t3.setText(countStr.charAt(2)+"");
            t4.setText(countStr.charAt(3)+"");
        }else{
            t1.setText(countStr.charAt(0)+"");
            t2.setText(countStr.charAt(1)+"");
            t3.setText(countStr.charAt(2)+"");
            t4.setText(countStr.substring(3)+"");
        }


    }

    @Override
    public void onStart() {
        Log.d(TAG, "onStart ..");
        super.onStart();
        udpReceiveThread = new UdpReceiveThread();
        udpReceiveThread.start();
    }

    private void showCompany() {
        if(mComponyJsonArray == null || mComponyJsonArray.size() <=0 ){

            findViewById(R.id.compony_tip).setVisibility(View.VISIBLE);
            for (int i = 0; i < 10; i++) {
                View view = mCompanyGroupView.getChildAt(i);
                ((TextView) view.findViewById(R.id.compony_name)).setText("");
                ((TextView) view.findViewById(R.id.compony_person_cnt)).setText("");
            }
            return;
        }

        findViewById(R.id.compony_tip).setVisibility(View.INVISIBLE);

        int showCnt = 10;
        if (mLastShowComponyIndex >= mComponyJsonArray.size())
            mLastShowComponyIndex = 0;
        for (int i = 0; i < showCnt; i++) {
            View view = mCompanyGroupView.getChildAt(i);
            ((TextView) view.findViewById(R.id.compony_name)).setText("");
            ((TextView) view.findViewById(R.id.compony_person_cnt)).setText("");
        }
        int index = 0;
        for (int i = mLastShowComponyIndex; i < mComponyJsonArray.size(); i++) {
            mLastShowComponyIndex++;
            if (showCnt <= 0) {
                return;
            }
            View view = mCompanyGroupView.getChildAt(index);
            JSONObject companyJo = mComponyJsonArray.getJSONObject(i);
            ((TextView) view.findViewById(R.id.compony_name)).setText(
                    companyJo.getString("name"));
            ((TextView) view.findViewById(R.id.compony_person_cnt)).setText(companyJo.getInteger("enterNum")+"");

            showCnt--;
            index++;
        }
    }

    private long mLastOkPressTime = 0;

    @Override
    public void onResume() {
        Log.d(TAG, "onResume ..");
        super.onResume();

        //DataManager.getInstance().resetTime();

        rootView.setFocusable(true);
        rootView.requestFocus();
//        rootView.setOnKeyListener(new View.OnKeyListener() {
//            @Override
//            public boolean onKey(View v, int keyCode, KeyEvent event) {
//
//                if (event.getAction() == KeyEvent.ACTION_UP) {
//                    return false;
//                }
//                Log.d(TAG, "rootView onKey keyCode = " + keyCode);
//
//                if (KeyEvent.KEYCODE_BACK == keyCode){
//                    finish();
//                    return true;
//                }
//                if (KeyEvent.KEYCODE_DPAD_CENTER == keyCode || KeyEvent.KEYCODE_ENTER == keyCode) {
//
//                    if (System.currentTimeMillis() - mLastOkPressTime < 1000) {
//                        showPopWindow();
//                    }
//                    mLastOkPressTime = System.currentTimeMillis();
//                }
//                return false;
//            }
//        });
//        rootView.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (System.currentTimeMillis() - mLastOkPressTime < 1000) {
//                    showPopWindow();
//                }
//                mLastOkPressTime = System.currentTimeMillis();
//            }
//        });

//        DataManager.getInstance().setmListener0(new DataListener.Data0Listener() {
//            @Override
//            public void onDataChanged(JSONObject jsonObject) {
//
//                Log.d(TAG, "项目名称 jsonObject = " + jsonObject.toJSONString());
//                try {
//                    String title = jsonObject.getJSONObject("data").getString("name");
//                    String url = jsonObject.getJSONObject("data").getString("homeLogo");
//
//                    ((TextView) findViewById(R.id.title)).setText(title);
//                    ImageUtil.getInstance().displayImage(mContext,url,mLeftLogoView,R.drawable.blank);
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//
//
//            }
//        });
//        DataManager.getInstance().setmListener1(new DataListener.Data1Listener() {
//            @Override
//            public void onDataChanged(JSONObject jsonObject) {
//
//                try {
//                    Log.d(TAG,"最新人员进出信息 jsonObject = "+jsonObject.toJSONString());
//                    JSONObject result = jsonObject.getJSONObject("data");
//                    ImageUtil.getInstance().displayImage(mContext, result.getString("image"), mPosterView, R.drawable.blank);
//                    mDetailView1.setText(result.getString("employeeName"));
//                    mDetailView2.setText(result.getString("employeeCompanyName"));
//                    mDetailView3.setText(result.getString("employeeTeamName"));
//                    mDetailView4.setText(result.getString("employeeWorkTypeName"));
//                    mDetailView5.setText(result.getString("employeePhone"));
//                    mDetailView6.setText(result.getString("employeeIdCard"));
//                    //1进，0出
//                    if(result.getInteger("way") == 1){
//                        mDetailView7.setText("进");
//                        mDetailView8.setText(result.getString("datetime"));
//                    }else{
//                        mDetailView7.setText("出");
//                        mDetailView8.setText(result.getString("datetime"));
//                    }
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//
//
//            }
//        });
//        DataManager.getInstance().setmListener2(new DataListener.Data2Listener() {
//            @Override
//            public void onDataChanged(JSONObject jsonObject) {
//
//                try {
//                    JSONArray jsonArray = jsonObject.getJSONArray("data");
//                    if (jsonArray == null || jsonArray.size() <= 0) {
//                        return;
//                    }
//                    mComponyJsonArray.clear();
//                    mLastShowComponyIndex = 0;
//
//                    for(int i= 0;i< jsonArray.size();i++){
//                        JSONObject companyJo = jsonArray.getJSONObject(i);
//                        int cnt = companyJo.getInteger("enterNum");
//                        if(cnt <= 0){
//                            continue;
//                        }
//                        mComponyJsonArray.add(companyJo);
//                    }
//                    showCompany();
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//
//
//            }
//        });
//        DataManager.getInstance().setmXsListener(new DataListener.Data5sListener() {
//            @Override
//            public void onXSecondPassed() {
//
//                try {
//                    showCompany();
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//            }
//        });
//        DataManager.getInstance().setmListener3(new DataListener.Data3Listener() {
//            @Override
//            public void onDataChanged(JSONObject jsonObject) {
//
//                try {
//                    JSONObject workerJo = jsonObject.getJSONObject("data").getJSONObject("labor");
//
//                    setCntText(workerJo.getInteger("enterNum"), mWoker1_1, mWoker1_2, mWoker1_3, mWoker1_4);
//                    setCntText(workerJo.getInteger("attendanceNum"), mWoker2_1, mWoker2_2, mWoker2_3, mWoker2_4);
//                    setCntText(workerJo.getInteger("realTimeNum"), mWoker3_1, mWoker3_2, mWoker3_3, mWoker3_4);
//
//                    JSONObject managerJo = jsonObject.getJSONObject("data").getJSONObject("admin");
//
//                    setCntText(managerJo.getInteger("enterNum"), mManager1_1, mManager1_2, mManager1_3, mManager1_4);
//                    setCntText(managerJo.getInteger("attendanceNum"), mManager2_1, mManager2_2, mManager2_3, mManager2_4);
//                    setCntText(managerJo.getInteger("realTimeNum"), mManager3_1, mManager3_2, mManager3_3, mManager3_4);
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//
//            }
//        });
//        DataManager.getInstance().setmListener4(new DataListener.Data4Listener() {
//            @Override
//            public void onDataChanged(JSONObject jsonObject) {
//                // Log.d(TAG,"人员年龄分布 jsonObject = "+jsonObject.toJSONString());
//                try {
//
//                    JSONArray jsonArray = jsonObject.getJSONArray("data");
//                    int age16_35=0,age36_45 =0, age46_55=0,age55_ = 0;
//
//                    if(jsonArray == null || jsonArray.size() <=0){
//                        return;
//                    }
//                    for(int i=0;i<jsonArray.size();i++){
//                        String ageStr = jsonArray.getJSONObject(i).getString("age");
//                        if("16-35岁".equalsIgnoreCase(ageStr)){
//                            age16_35 =  jsonArray.getJSONObject(i).getInteger("value");
//                        }else if("36-45岁".equalsIgnoreCase(ageStr)){
//                            age36_45 =  jsonArray.getJSONObject(i).getInteger("value");
//                        }else if("46-55岁".equalsIgnoreCase(ageStr)){
//                            age46_55 =  jsonArray.getJSONObject(i).getInteger("value");
//                        }else if("55岁以上".equalsIgnoreCase(ageStr)){
//                            age55_ =  jsonArray.getJSONObject(i).getInteger("value");
//                        }
//                    }
//                    int all = age16_35+age36_45 + age46_55+age55_;
//                    if (all <= 0) {
//                        return;
//                    }
//                    int maxLenth = ViewAdjust.getWidthPxAdjust(mContext, 250);
//                    mAageIv1.getLayoutParams().width = (maxLenth * age16_35 / all);
//                    mAageIv2.getLayoutParams().width = (maxLenth * age36_45 / all);
//                    mAageIv3.getLayoutParams().width = (maxLenth * age46_55 / all);
//                    mAageIv4.getLayoutParams().width = (maxLenth * age55_ / all);
//                    int p1=age16_35 * 100 / all,p2=age36_45 * 100 / all,p3=age46_55 * 100 / all;
//                    mAagePercent1.setText(age16_35 * 100 / all + "%");
//                    mAagePercent2.setText(age36_45 * 100 / all + "%");
//                    mAagePercent3.setText(age46_55 * 100 / all + "%");
//                    mAagePercent4.setText((100-p1-p2-p3) + "%");
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//
//            }
//        });
//        DataManager.getInstance().setmListener5(new DataListener.Data5Listener() {
//            @Override
//            public void onDataChanged(JSONObject jsonObject) {
//                //Log.d(TAG,"人员性别分布 jsonObject = "+jsonObject.toJSONString());
//                try {
//                    JSONArray jsonArray = jsonObject.getJSONArray("data");
//                    int femaleCnt = 0;
//                    int maleCnt = 0;
//                    for(int i=0;i< jsonArray.size();i++){
//                        Integer sex = jsonArray.getJSONObject(i).getInteger("sex");
//                        if( sex != null && sex== 1){
//                            femaleCnt = jsonArray.getJSONObject(i).getInteger("value");
//                        }else{
//                            maleCnt = jsonArray.getJSONObject(i).getInteger("value");
//                        }
//                    }
//                    if (maleCnt + femaleCnt <= 0) {
//                        return;
//                    }
//                    int mPercent = maleCnt * 100 / (maleCnt + femaleCnt);
//                    int fPercent = 100-mPercent;//femaleCnt * 100 / (maleCnt + femaleCnt);
//                    mSexMale.setText("男 " + maleCnt + "  " + mPercent + "%");
//                    mSexFemale.setText("女 " + femaleCnt + "  " + fPercent + "%");
//                    setMPercent(mPercent);
//                    setFPercent(100-mPercent);
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//
//
//            }
//        });
//        DataManager.getInstance().setmListener6(new DataListener.Data6Listener() {
//            @Override
//            public void onDataChanged(JSONObject jsonObject) {
//                //Log.d(TAG, "工种分布 jsonObject = " + jsonObject.toJSONString());
//                try {
//                    setData6(jsonObject);
//                }catch (Exception e){
//                    e.printStackTrace();
//                }
//
//            }
//        });

       // checkUpdate();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {

        if (requestCode == 1) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                checkUpdate();
            } else {
                Log.e(TAG, "onRequestPermissionsResult: 申请权限已拒绝");
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private  void checkUpdate(){
        final long currVcode = Util.getAppVersionCode(mContext);
        new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    String jsonStr = OkHttpUtil.executeGet(ProjectConfig.checkUrl,null,null);
                    if(Util.isEmpty(jsonStr)){
                        Log.e(TAG,"check_json empty!!!");
                        return;
                    }
                    JSONObject jsonObject = JSONObject.parseObject(jsonStr);
                    long vCode = jsonObject.getLongValue("versionCode");
                    String url = jsonObject.getString("url");

                    Log.d(TAG,"check_json = "+jsonStr);
                    if(vCode > currVcode && !Util.isEmpty(url)){

                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                            if(ContextCompat.checkSelfPermission(mContext,"android.permission.WRITE_EXTERNAL_STORAGE")
                                    != PackageManager.PERMISSION_GRANTED){

                                ActivityCompat.requestPermissions(mContext,
                                        new String[]{
                                                "android.permission.WRITE_EXTERNAL_STORAGE",
                                                "android.permission.READ_EXTERNAL_STORAGE",
                                                "android.permission.REQUEST_INSTALL_PACKAGES",
                                                "android.permission.REPLACE_EXISTING_PACKAGE",
                                        },1);
                                return;
                            }
                        }
                        Util.showToast(mContext,"检测到新版本,正在后台下载新版本,请稍后!");
                        UtilHttp.download(mContext,url,"jxtmpV2.apk");
                    }

                }catch (Exception e){
                    e.printStackTrace();
                }


            }
        }).start();

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(DownloadProgressEvent event) {

        if(event.getName().equals("finish")){
            Util.installApk(mContext,"tushen.apk");
        }else{
            Util.showToast(mContext,"正在下载升级版,进度 "+(event.getDownload()*100/event.getSize())+"%");
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        Log.d(TAG, "onStop ..");
        listenStatus = false;
        receiveSocket.close();
        udpReceiveThread.interrupt();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        Log.d(TAG, "onDestroy ..");
    }

    /**
     * Instances of static inner classes do not hold an implicit
     * reference to their outer class.
     */
//    private static class MyHandler extends Handler {
//        private final WeakReference<MainActivity> mActivity;
//
//        public MyHandler(MainActivity activity) {
//            mActivity = new WeakReference<>(activity);
//        }
//
//        @Override
//        public void handleMessage(Message msg) {
//
//            MainActivity activity = mActivity.get();
//            //Log.d(TAG,"handleMessage activity = "+activity+" message = "+(msg!= null ? msg.what:"null"));
//
//            if (activity == null || msg == null) {
//                return;
//            }
//
//            switch (msg.what) {
//                case 0:
//                    if (activity.mTimeTextView != null) {
//                        activity.mTimeTextView.refreashUI();
//                        activity.mHandler.sendEmptyMessageDelayed(0, 1000);
//                    }
//                    break;
//
//            }
//        }
//    }

    private int[] colorArr = {
            ColorUtil.COLOR_1, ColorUtil.COLOR_2, ColorUtil.COLOR_3, ColorUtil.COLOR_4,
            ColorUtil.COLOR_5, ColorUtil.COLOR_6, ColorUtil.COLOR_7, ColorUtil.COLOR_8,
            ColorUtil.COLOR_9, ColorUtil.COLOR_10,
    };


    private void setData6(JSONObject jsonObject) {

        JSONArray jsonArray = jsonObject.getJSONArray("data");
        if (jsonArray == null || jsonArray.size() <= 0) {
            mPieChart.setVisibility(View.INVISIBLE);
            mPieGridView.setVisibility(View.INVISIBLE);
            findViewById(R.id.all_cnt).setVisibility(View.INVISIBLE);
            ((TextView) findViewById(R.id.all_cnt_name)).setText("暂无数据");
            return;
        }
        List<IPieElement> list = new ArrayList<>();
        mPieChart.setData(list);

        JSONArray newJsonArr = new JSONArray();
        for (int i = 0; i < jsonArray.size(); i++) {
            int cnt = jsonArray.getJSONObject(i).getInteger("enterNum");
            if(cnt <= 0){
                continue;
            }
            newJsonArr.add(jsonArray.getJSONObject(i));
        }

        if(newJsonArr.size() <= 0 ){
            mPieChart.setVisibility(View.INVISIBLE);
            mPieGridView.setVisibility(View.INVISIBLE);
            findViewById(R.id.all_cnt).setVisibility(View.INVISIBLE);
            ((TextView) findViewById(R.id.all_cnt_name)).setText("暂无数据");
            return;
        }else {
            mPieChart.setVisibility(View.VISIBLE);
            mPieGridView.setVisibility(View.VISIBLE);
            findViewById(R.id.all_cnt).setVisibility(View.VISIBLE);
            ((TextView) findViewById(R.id.all_cnt_name)).setText("总人数");
        }
        ArrayList<String> nameList = new ArrayList<>();
        ArrayList<Integer> colorList = new ArrayList<>();

        LinkedHashMap<Integer, Integer> maxMap = new LinkedHashMap<>();
        int all = 0;
        int calcCnt = 0;
        for (int i = 0; i < newJsonArr.size(); i++) {
            int max = newJsonArr.getJSONObject(i).getInteger("enterNum");
            int maxPos = i;
            all += max;
            for (int k = 0; k < newJsonArr.size(); k++) {

                int cntk = newJsonArr.getJSONObject(k).getInteger("enterNum");
                if (i == k) {
                    continue;
                }
                if (cntk > max && maxMap.get(k) == null) {
                    max = cntk;
                    maxPos = k;
                }

            }
            if (maxMap.get(maxPos) == null) {
                maxMap.put(maxPos, max);
            }
        }
        Log.d(TAG, "maxmap: " + maxMap);
        int index = 0;
        for (Map.Entry<Integer, Integer> entry : maxMap.entrySet()) {

            int pos = entry.getKey();
            int cnt = entry.getValue();
            Log.d(TAG, "setData6 pos  = " + pos + " cnt = " + cnt);
            String name = newJsonArr.getJSONObject(pos).getString("name") + " " + cnt + "人";
            if (index < ProjectConfig.PIE_CHART_MAX_CNT - 1) {
                index++;
                calcCnt += cnt;
                nameList.add(name);
                colorList.add(colorArr[index]);
                list.add(new TestEntity(cnt, colorArr[index], name));
            } else {
                break;
            }

        }

        Log.d(TAG, "setData6 list = " + list);
        if (all != calcCnt) {
            list.add(new TestEntity(all - calcCnt, colorArr[ProjectConfig.PIE_CHART_MAX_CNT - 1],
                    "其他人员 " + (all - calcCnt) + "人"));
            nameList.add("其他人员 " + (all - calcCnt) + "人");
            colorList.add(colorArr[ProjectConfig.PIE_CHART_MAX_CNT - 1]);
        }

        mPieChart.setData(list);
        mPieChart.setTitleText(all + " 总人数");
        mPieChart.setAnimEnable(false);
        mPieChart.enableLegend(false);

        ((TextView) findViewById(R.id.all_cnt)).setText(all + "");

        ((ItemAdapter) mPieGridView.getAdapter()).setList(nameList, colorList);

    }

    private void setMPercent(int percent) {

        ((ImageView) findViewById(R.id.m1)).setImageResource(R.drawable.m2);
        ((ImageView) findViewById(R.id.m2)).setImageResource(R.drawable.m2);
        ((ImageView) findViewById(R.id.m3)).setImageResource(R.drawable.m2);
        ((ImageView) findViewById(R.id.m4)).setImageResource(R.drawable.m2);
        ((ImageView) findViewById(R.id.m5)).setImageResource(R.drawable.m2);

        if (percent > 0) {
            ((ImageView) findViewById(R.id.m1)).setImageResource(R.drawable.m1);
        }
        if (percent >= 40) {
            ((ImageView) findViewById(R.id.m2)).setImageResource(R.drawable.m1);
        }
        if (percent >= 60) {
            ((ImageView) findViewById(R.id.m3)).setImageResource(R.drawable.m1);
        }
        if (percent >= 80) {
            ((ImageView) findViewById(R.id.m4)).setImageResource(R.drawable.m1);
        }
        if (percent >= 100) {
            ((ImageView) findViewById(R.id.m5)).setImageResource(R.drawable.m1);
        }
    }

    private void setFPercent(int percent) {

        ((ImageView) findViewById(R.id.f1)).setImageResource(R.drawable.f2);
        ((ImageView) findViewById(R.id.f2)).setImageResource(R.drawable.f2);
        ((ImageView) findViewById(R.id.f3)).setImageResource(R.drawable.f2);
        ((ImageView) findViewById(R.id.f4)).setImageResource(R.drawable.f2);
        ((ImageView) findViewById(R.id.f5)).setImageResource(R.drawable.f2);

        if (percent > 0) {
            ((ImageView) findViewById(R.id.f1)).setImageResource(R.drawable.f1);
        }
        if (percent >= 40) {
            ((ImageView) findViewById(R.id.f2)).setImageResource(R.drawable.f1);
        }
        if (percent >= 60) {
            ((ImageView) findViewById(R.id.f3)).setImageResource(R.drawable.f1);
        }
        if (percent >= 80) {
            ((ImageView) findViewById(R.id.f4)).setImageResource(R.drawable.f1);
        }
        if (percent >= 100) {
            ((ImageView) findViewById(R.id.f5)).setImageResource(R.drawable.f1);
        }
    }

    @Override
    public void onAttachedToWindow() {
        super.onAttachedToWindow();
        //在这个方法调用之前，view都没有被attach到ViewRoot上（也就没有show的概念），显示工作则是由WindowManagerService去控制的
        Log.d(TAG, "onAttachedToWindow called..mContext = " + mContext);
    }

    @Override
    public void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        Log.d(TAG, "onDetachedFromWindow called..mContext = " + mContext);
    }

    private final static int RECEIVE_PORT = 53212;

    private boolean listenStatus = true;

    private String receiveInfo;

    private DatagramSocket receiveSocket;

    public class UdpReceiveThread extends Thread {

        private final String TAG = "UdpReceiveThread";

        public UdpReceiveThread(){
        }

        @Override
        public void run() {
            Log.d(TAG, "receiving... ");
            try {
                receiveSocket = new DatagramSocket(RECEIVE_PORT); //
                while (listenStatus){
                    byte data[] = new byte[1024*8];
                    DatagramPacket packet = new DatagramPacket(data, data.length);
                    receiveSocket.receive(packet); // 阻塞式，接收发送方的packet
                    //取出数据长度
                    int len = packet.getLength();

                    byte[] packetByte = packet.getData();
                    byte[] messageByte = new byte[len];
                    System.arraycopy(packetByte, 0, messageByte, 0, len);

                    receiveInfo = AesEncryptUtils.decryptByte(messageByte);
                    Log.d(TAG, "received:  " + receiveInfo);

                    Message msg = Message.obtain();
                    msg.obj = receiveInfo;
                    handler.sendMessage(msg);

                }
            } catch (Exception e) {
                e.printStackTrace();
                Log.d(TAG, "run: " + e.getMessage());
            }

        }
    }

    public class MessageHandler extends Handler {

        String deviceIp = "";

        private final WeakReference<MainActivity> mActivity;

        public MessageHandler(MainActivity activity) {
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            MainActivity activity = mActivity.get();

            if (activity == null || msg == null || msg.obj == null) {
                return;
            }

            String obj = (String) msg.obj;
            this.handleMessage(obj);
        }

        private void handleMessage(String message) {
            JSONObject jsonObject = JSONObject.parseObject(message);
            Log.d(TAG, " massage: " + jsonObject);
            if (jsonObject != null){
                String type = jsonObject.getString("Type");
                JSONObject data = jsonObject.getJSONObject("Data");
                String devID = jsonObject.getString("DevID");
                switch (type){
                    case "IAmAlive":
                      hanleHeartbeat(data);
                        break;
                    case "ReportRecord":
                      hanleRecord(data);
                        break;
                    case "StatChange":
                      hanleStatChange(data);
                        break;
                }
            }else{
                Log.d(TAG, "空消息");
            }

        }

        private void hanleStatChange(JSONObject data) {
            try{
                //登记人员分类
                JSONObject personByClassify = data.getJSONObject("PersonByClassify");
                Optional.ofNullable(personByClassify).ifPresent(personbyClassify -> {
                    personbyClassify.entrySet().forEach(item -> {
                        JSONObject value = JSONObject.parseObject(item.getValue().toString());
                        if ("普通工人".equals(value.getString("Name"))){
                            Log.d(TAG,value.getString("Name") + ": " + value.getInteger("Num"));
                            setCntText(value.getInteger("Num"), mWoker1_1, mWoker1_2, mWoker1_3, mWoker1_4);
                        }else{
                            Log.d(TAG,value.getString("Name") + ": " + value.getInteger("Num"));
                            setCntText(value.getInteger("Num"), mManager1_1, mManager1_2, mManager1_3, mManager1_4);
                        }
                    });
                });

                //在场人员分类
                JSONObject presentPersonByClassify = data.getJSONObject("PersentPersonByClassify");
                Optional.ofNullable(presentPersonByClassify).ifPresent(presentPerson -> {
                    presentPerson.entrySet().forEach(item -> {
                        JSONObject value = JSONObject.parseObject(item.getValue().toString());
                        if ("普通工人".equals(value.getString("Name"))){
                            Log.d(TAG,value.getString("Name") + ": " + value.getInteger("Num"));
                            setCntText(value.getInteger("Num"), mWoker2_1, mWoker2_2, mWoker2_3, mWoker2_4);
                            //setCntText(value.getInteger("Num"), mWoker3_1, mWoker3_2, mWoker3_3, mWoker3_4);
                        }else{
                            Log.d(TAG,value.getString("Name") + ": " + value.getInteger("Num"));
                            setCntText(value.getInteger("Num"), mManager2_1, mManager2_2, mManager2_3, mManager2_4);
                            //setCntText(value.getInteger("Num"), mManager3_1, mManager3_2, mManager3_3, mManager3_4);
                        }
                    });
                });
            }catch (Exception e){
                e.printStackTrace();
                Log.e(TAG, "劳务人员管理人员分类展示出错" + e.getMessage());
            }

            //单位人员考勤
            try{
                JSONObject presentPersonByCompany = data.getJSONObject("PresentPersonByCompany");
                Optional.ofNullable(presentPersonByCompany).ifPresent(ppByCompany -> {
                    mComponyJsonArray.clear();
                    mLastShowComponyIndex = 0;
                    ppByCompany.entrySet().forEach(item -> {
                        JSONObject value = JSONObject.parseObject(item.getValue().toString());
                        Integer num = value.getInteger("Num");
                        if(num > 0){
                            JSONObject companyJson = new JSONObject();
                            companyJson.put("enterNum",num);
                            companyJson.put("name",value.getString("Name"));
                            mComponyJsonArray.add(companyJson);
                        }
                    });
                    showCompany();
                });
            }catch (Exception e){
                e.printStackTrace();
                Log.e(TAG, "单位人员考勤展示出错" + e.getMessage());
            }

            //现场工种
            try{
                JSONObject presentPersonByWorkType = data.getJSONObject("PresentPersonByWorkType");
                Optional.ofNullable(presentPersonByWorkType).ifPresent(ppByWorkType -> {
                    JSONObject jsonObject = new JSONObject();
                    JSONArray workTypeJsonArray =  new JSONArray();
                    ppByWorkType.entrySet().forEach(item -> {
                        JSONObject value = JSONObject.parseObject(item.getValue().toString());
                        Integer num = value.getInteger("Num");
                        String name = value.getString("Name");
                        if(num > 0){
                            JSONObject workTypeJson = new JSONObject();
                            workTypeJson.put("enterNum",num);
                            workTypeJson.put("name", name);
                            workTypeJsonArray.add(workTypeJson);
                        }
                    });
                    jsonObject.put("data",workTypeJsonArray);
                    Log.d(TAG, workTypeJsonArray.toJSONString());
                    setData6(jsonObject);
                });
            }catch (Exception e){
                e.printStackTrace();
                Log.e(TAG, "现场工种展示出错" + e.getMessage());
            }


        }

        //设备刷脸实时考勤
        private void hanleRecord(JSONObject data) {
            try{
                String CustomID = data.getString("CustomID");
                String CardID = data.getString("CardID");
                String FaceImgPath = data.getString("FaceImgPath");
                String UserName = data.getString("UserName");
                Long timeStamp = data.getLong("TimeStamp");
                boolean dir = data.getBoolean("Dir");
                String Company = data.getString("Company");
                String WorkType = data.getString("WorkType");
                String TeamName = data.getString("TeamName");
                String faceImgPath = "http://" +deviceIp + FaceImgPath.replace("/database","");

                ImageUtil.getInstance().displayImage(mContext, faceImgPath, mPosterView, R.drawable.blank);
                mDetailView1.setText("默认参数");
                Optional.ofNullable(UserName).ifPresent(username ->{
                    mDetailView1.setText(username);
                });

                mDetailView2.setText("默认参数");
                Optional.ofNullable(Company).ifPresent(company ->{
                    mDetailView2.setText(company);
                });

                mDetailView3.setText("默认参数");
                Optional.ofNullable(TeamName).ifPresent(teamName ->{
                    mDetailView3.setText(teamName);
                });

                mDetailView4.setText("默认参数");
                Optional.ofNullable(WorkType).ifPresent(workType ->{
                    mDetailView4.setText(workType);
                });

                mDetailView5.setText("默认参数");//phone
                mDetailView6.setText("默认参数");//idcard
                Optional.ofNullable(CardID).ifPresent(cardID ->{
                    mDetailView6.setText(getMixString(cardID));
                });
                String datetime = DateUtil.formatDate(timeStamp == null ? 0L:timeStamp);
                //true进，false出
                if(dir){
                    mDetailView7.setText("进");
                    mDetailView8.setText(datetime);
                }else{
                    mDetailView7.setText("出");
                    mDetailView8.setText(datetime);
                }
            } catch (Exception e){
                e.printStackTrace();
                Log.e(TAG, "人员进出详细信息展示出错" + e.getMessage());
            }

        }

        private void hanleHeartbeat(JSONObject data) {
            Log.d(TAG, "alive: "+ data.toJSONString());
            deviceIp = data.getString("IP");
            ((TextView) findViewById(R.id.title)).setText(deviceIp);
        }

    }

}
